﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using SIR.Common.Condition;
using SIR.DAL;
using SIR.Entities.Implementations;
using System.IO;

namespace SIR.Services.Tests
{
	[TestClass]
	public class ImageProcessingServiceTest
	{
		[TestInitialize]
		public void InitalizeTest()
		{
			// connect to the database if neccesary
			if (!DAL.DataServer.IsConnected())
				DAL.DataServer.Connect(System.Configuration.ConfigurationManager.ConnectionStrings["SIR"].ConnectionString);
			// get images to load
			var files = Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\..\\SIR.Services.Tests\\Test Images"));
			Image image;
			string errorMessage;
			// load each image to the system
			foreach (var file in files)
			{
				var bytes = File.ReadAllBytes(file);
				Image.SaveImage(1, 0, Path.GetFileNameWithoutExtension(file), "JPEG", bytes.Length, bytes,
					true, Common.ProcessingPriority.Search, out image, out errorMessage);
			}
		}

		[TestCleanup]
		public void CleanupTest()
		{
			// fine all images and delete them
			var images = DAL.DataServer.Find<Image>(new Predicate("UserId", 1, PredicateOperator.EqualTo)).Results;
			foreach (var image in images)
			{
				image.IsDeleted = true;
				DAL.DataServer.Save<Image>(image);
			}
			// disconnect from the database
			DAL.DataServer.Disconnect();
		}

		[TestMethod]
		[SIRTestCategory(typeof(Area.ImageProcessing), Area.ImageProcessing.AnalyzeImage, 1, typeof(ImageProcessing.Processing))]
		public void ServiceProcessesImagesInTheQueue()
		{
			// Add Items to Queue
			var startCount = DataServer.Find<QueuedImage>(new Predicate("StatusId", 0, PredicateOperator.EqualTo)).Results.Count;
			// Start Processing
			while (ImageProcessing.Processing.ProcessNextImage())
			{
				// Wait for Processing
			}
			// Check for shorter queue
			Assert.IsTrue(DataServer.Find<QueuedImage>(new Predicate("StatusId", 0, PredicateOperator.EqualTo)).Results.Count < startCount,
				"Queue is not being processed, count is still the same");
		}

		[TestMethod]
		[SIRTestCategory(typeof(Area.ImageProcessing), Area.ImageProcessing.AnalyzeImage, 1, typeof(ImageProcessing.Processing))]
		public void ServiceAnalyzesImagesInTheQueue()
		{
			// Add Items to Queue
			var startCount = DataServer.Find<ImageAnalysis>().Results.Count;
			// Start Processing
			while (ImageProcessing.Processing.ProcessNextImage())
			{
				// Wait for Processing
			}
			// Check for more analyzed image records
			Assert.IsTrue(DataServer.Find<ImageAnalysis>().Results.Count > startCount,
				"Queue is not being processed, count is still the same");

		}
	}
}
